package concurrency;


import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeDemo2 {
    private static Unsafe unsafe;

    private static final long stateOffset;

    private volatile long state = 0;

    static {
        try {
            //使用反射获取Unsafe的成员变量theUnsafe
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            //设置为可存取
            field.setAccessible(true);
            stateOffset = unsafe.objectFieldOffset(UnsafeDemo2.class.getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            System.out.println(e.getLocalizedMessage());
            throw new Error(e);
        }
    }

    public static void main(String[] args) {
        UnsafeDemo2 unsafeDemo = new UnsafeDemo2();
        Boolean success = unsafe.compareAndSwapInt(unsafeDemo, stateOffset, 0, 1);
        System.out.println(success);
    }
}
